package it.polito.connectedcar.network;

import java.net.InetAddress;
import java.util.List;

import de.uniluebeck.itm.tcpip.Storage;

public abstract class Message {

	private InetAddress sourceAddress;
	private EntityType targetType;
	private Storage storage;
	private long timestamp;
	
	
	protected Message(EntityType targetType)
	{
		this.targetType=targetType;
		storage = new Storage();
	}
	protected Message(EntityType targetType,byte[] initData)
	{
		this.targetType=targetType;
		storage = new Storage(initData);
		_convertFromData();
	}
	private void _convertFromData()
	{
		targetType = EntityType.fromEntityCode(storage.readByte());
		timestamp = storage.readLong();
		convertFromData(storage);
	}
	
	public EntityType getTargetType()
	{
		return this.targetType;
	}
	
	public InetAddress getSourceAddress()
	{
		return sourceAddress;
	}
	
	public void setSourceAddress(InetAddress sourceAddress)
	{
		this.sourceAddress=sourceAddress;
	}
	
	protected abstract void convertToData(Storage st);
	
	
	private void finalizeToStorage()
	{
		storage.reset();
		storage.writeByte(targetType.getTypeCode());
		storage.writeLong(timestamp);
		
		convertToData(storage);
	}
	
	public byte[] getMessageAsBytes()
	{
		finalizeToStorage();
		List<Byte> bytesList = storage.getStorageList();
		byte[] bytes = new byte[bytesList.size()];
		
		for(int i=0;i<bytesList.size();i++)
		{
			bytes[i]= bytesList.get(i).byteValue();
		}
		return bytes;
	}
	
	public void empty()
	{
		storage.reset();
	}
	public void destroy()
	{
		empty();
		storage=null;
		sourceAddress = null;
	}
	
	public long getTimestamp()
	{
		return this.timestamp;
	}
	public void setTimestamp(long timestamp)
	{
		this.timestamp = timestamp;
	}
	
	/**
	 * 
	 */
	protected abstract void convertFromData(Storage st);
	
}
